package com.phkj.qdh.ui.fragment

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.phkj.qdh.R
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentHomeBinding
import com.phkj.qdh.ui.adapter.HomeNotificationAdapter
import com.phkj.qdh.ui.fragment.baseinspect.BaseInspectSelectFragment
import com.phkj.qdh.ui.fragment.failover.FailoverSelectFragment
import com.phkj.qdh.ui.fragment.lawinspect.LawInspectSelectFragment
import com.phkj.qdh.ui.fragment.teaminspect.TeamInspectSelectFragment
import com.phkj.qdh.ui.fragment.usecar.UseCarMainFragment
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest

/**
 * 首页
 */
class HomeFragment : Fragment() {

    private val pageInfo = PageInfo()

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private lateinit var vm: HomeVM

    private val homeNotificationAdapter by lazy { HomeNotificationAdapter() }
    private lateinit var helper: QuickAdapterHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {}
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getHomeProvider())[HomeVM::class.java]
        return binding.root
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            rvHome.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(
                    MyItemDecoration(
                        color = ContextCompat.getColor(requireContext(), R.color.backgound)
                    )
                )
            }
            tvBaseInspect.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("base")
                    replace(id, BaseInspectSelectFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            tvTeamInspect.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("team")
                    replace(id, TeamInspectSelectFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }/*

                                val channelId = createNotificationChannel(
                                    requireContext(), "jwt", "jwt", NotificationManager.IMPORTANCE_HIGH
                                )
                                val notification = if (channelId == null) {
                                    NotificationCompat.Builder(requireContext())
                                } else {
                                    NotificationCompat.Builder(requireContext(), channelId)
                                }
                                notification.setContentText("警务通").setSettingsText("fuyjagsgufjkhaksoljhf")
                                    .setSmallIcon(R.mipmap.ic_launcher).setAutoCancel(true)

                                val not = NotificationManagerCompat.from(requireContext())

                                if (ActivityCompat.checkSelfPermission(
                                        requireContext(), Manifest.permission.POST_NOTIFICATIONS
                                    ) == PackageManager.PERMISSION_GRANTED
                                ) {
                                    not.notify(100, notification.build())
                                }

                */

            }
            tvEnforcementInspect.setOnClickListener { //执法
                parentFragmentManager.commit {
                    addToBackStack("law")
                    replace(id, LawInspectSelectFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            tvFailoverIncentive.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("fail")
                    replace(id, FailoverSelectFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            tvUserTheCar.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("car")
                    replace(id, UseCarMainFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            srlHome.setOnRefreshListener {
                fresh()
            }
        }

        initAdapter()

    }


    private fun initAdapter() {
        // 使用默认的"加载更多"的样式
        helper = QuickAdapterHelper.Builder(homeNotificationAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    pageInfo.nextPage()
                    getNotificationList()
                }

                override fun onFailRetry() {
                    getNotificationList()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlHome.isRefreshing
                }
            }).build()

        // 设置预加载，请调用以下方法
        binding.rvHome.adapter = helper.adapter

        homeNotificationAdapter.setOnItemClickListener { a, _, pos ->
            a.getItem(pos)?.let { bean ->
                parentFragmentManager.commit {
                    addToBackStack("notification")
                    replace(id, HomeNotificationDetailFragment.newInstance(bean, ""))
                    setReorderingAllowed(true)
                }
            }

        }

        launchAndRepeatWithViewLifecycle {
            vm.homeNotificationList.collectLatest {
                if (pageInfo.isFirstPage) {
                    homeNotificationAdapter.submitList(it)
                } else {
                    homeNotificationAdapter.addAll(it)
                }

                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    helper.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    helper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.state.collectLatest {
                binding.srlHome.isRefreshing = false
            }
        }

        getNotificationList()
    }


    private fun getNotificationList() {
        val map = HashMap<String, Any?>()
        map["page"] = pageInfo.page
        map["size"] = PAGE_SIZE
        vm.getHomeNotificationList(map)

    }

    override fun onStart() {
        super.onStart()
//        binding.srlHome.isRefreshing = true
//        getNotificationList()
    }


    private fun fresh() {
        pageInfo.reset()
        helper.trailingLoadState = LoadState.None
        getNotificationList()
    }


    companion object {
        @JvmStatic
        fun newInstance() = HomeFragment().apply {
            arguments = Bundle().apply {}
        }
    }
}